package runesim.node;
import java.util.*;
import runesim.shared.Configuration;
import runesim.shared.Prompt;
import runesim.node.model.World;
import runesim.node.packethandler.*;
import runesim.node.test.DebuggingPacketHandler;
import runesim.node.test.QuietPacketHandler;
import runesim.node.util.Logger;
public class NodeServer {
	
	private static final Map<Integer, String> packetNames = new HashMap<Integer, String>();
	
	public static void main(String[] args) throws Exception {
		Configuration.load();
		
		try {
			ScriptMap.load();
		} catch(Exception e){ 
			e.printStackTrace();
			System.out.println("Failed loading packet definitions; exiting.");
			System.exit(1);
		}
		
		Prompt.println("Loaded configuration");
		
		World.loadWorld(new GenericWorldLoader());
		ServerSocketBinder s = new ServerSocketBinder();
		
		for(int i = 0; i < handlers.length && i < handleIds.length; i++) {
			PacketHandler h = handlers[i];
			List<GameEngine.SingleBoundPacketHandler> overwritten = s.getGameEngine().registerPacketHandler(h, handleIds[i]);
			if(overwritten != null)
				Logger.err("Error! Overwritten packet handlers: " + overwritten.toString());
		}
		Logger.log("Added packet handlers");
		s.start(Integer.parseInt(Configuration.get().getProperty("node_port", "43594")));
		Logger.log("Listening on port " + Integer.parseInt(Configuration.get().getProperty("node_port", "43594")));
	}
	
	static {
		int[] knownIds = new int[packetNames.size()];
		Iterator<Integer> keys = packetNames.keySet().iterator();
		for(int i = 0; i < knownIds.length; i++) {
			knownIds[i] = keys.next();
		}
		
		handleIds = new int[][] {
				{0, 1, 86, 210, 121, 3, 241}, //Quiet packets (don't want to hear about them
				{226, 78, 148, 183, 230, 136, 189, 152, 200, 85, 165, 238, 150, 36, 246, 77}, //Anti-BOT packets
				knownIds, //Not sure how these get loaded
				{164, 98, 248}, //Walking packets
				{185},  //Action button packets
				{4},  //Chat packets
				{103}, //JMOD command packets
				{132,252,70}, //Object click packets
				{202}, //Idle logout
				{87}, //Drop item on floor
				{214}, //Swap slot
				{41}, //Wield item
				{145,117,43,129,135},
				{53}, //IOI
				};
		handlers = new PacketHandler[] {
				new QuietPacketHandler(),
				new QuietPacketHandler(),
				new DebuggingPacketHandler(packetNames), 
				new Walking(), 
				new ActionButton(), 
				new PublicChat(), 
				new CommandHandler(),
				new WorldObjectHandler(),
				new IdleLogout(),
				new DropItem(),
				new SwapSlot(),
				new WieldItem(),
				new InterfaceItemController(),
				new ItemOnItem()
				};
	}
	
	private static final PacketHandler[] handlers;
	private static final int[][] handleIds;
}